package org.zachary.commonservice.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.zachary.commonservice.entity.OverdueRecord;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/overdue/stream")
public class OverduePushController {

    // 保存每个客户端连接
    private final Map<String, SseEmitter> clientMap = new ConcurrentHashMap<>();

    // 客户端连接 SSE
    @GetMapping("/subscribe")
    public SseEmitter subscribe(@RequestParam String clientId) {
        SseEmitter emitter = new SseEmitter(0L); // 永不超时
        clientMap.put(clientId, emitter);
        System.out.println("连接成功,id="+clientId);

        // 移除已断开连接
        emitter.onCompletion(() -> clientMap.remove(clientId));
        emitter.onTimeout(() -> clientMap.remove(clientId));
        emitter.onError((e) -> clientMap.remove(clientId));

        return emitter;
    }

    // 主动推送
    public void pushOverdueUpdate(OverdueRecord record) {
        String message = "用户 " + record.getUserId() + " 的逾期记录已完成付款";

        for (SseEmitter emitter : clientMap.values()) {
            try {
                emitter.send(SseEmitter.event()
                        .name("overdue-update")
                        .data(record));
                System.out.println("消息推送成功,data="+record);
            } catch (IOException e) {
                emitter.completeWithError(e);
            }
        }
    }
}

